<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit" class="my-form">
      <van-field
        v-model="loginForm.loginname"
        name="用户名"
        label="手机号"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号不合法' }
        ]"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /\S{6,}$/, message: '密码至少6位' }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
import { showSuccessToast, showFailToast } from 'vant'
const router = useRouter()
const userStore = useUserStore()
const loginForm = reactive({
  loginname: '17704051019',
  password: '123456'
})

// 提交
const onSubmit = async () => {
  try {
    const res = await login(loginForm)
    if (res.code === 200) {
      // 保存token到仓库中
      userStore.setUserInfo(res.data)

      // 提示
      showSuccessToast({
        message: res.message,
        duration: 800,
        onClose: () => {
          // 跳转到首页
          router.push('/')
        }
      })
    } else {
      showFailToast(res.message)
    }
  } catch (error) {}
}

// 返回
const onClickLeft = () => {
  router.back()
}
</script>
